const log4js = require('koa-log4');
const logger = log4js.getLogger('services::staff');
const bson = require('bson');
const DBRef = bson.DBRef;
const helper = require('mongoskin').helper;
const db = require('../mongodb');

const findAll = async () => {
    return new Promise(function (resolve, reject) {
        db.staff.find().toArray(async (err, result) => {
            if (!err) {
                resolve(result);
            } else {
                reject(err);
            }
        });
    });
};


const findBySite = async (site_id) => {

    let site;

    // 处理DBRef字段
    if (site_id) {
        site = new DBRef('site', helper.toObjectID(site_id));
    }

    let fields = {site: 0, _id: 0};

    return new Promise(function (resolve, reject) {
        db.staff.find({"site": site}, fields).toArray(async (err, result) => {
            if (!err) {
                resolve(result);
            } else {
                reject(err);
            }
        });
    });
};

const find = async (q) => {

    let query = q['query'];
    let sort = q['sort'];
    let page = q['page'];

    let pageIndex = page['index'];
    let pageSize = page['size'];
    let skip = (pageIndex - 1) * pageSize;

    //-----------------notice start--------------

    // 处理DBRef字段
    if (query.site) {
        query.site = new DBRef('site', helper.toObjectID(query.site));
    }

    // 处理ObjectId字段
    if (query._id) {
        query._id = helper.toObjectID(query._id)
    }

    //-----------------notice end--------------

    // 查询数量
    let query_count = new Promise((resolve, reject) => {
        db.staff.count(query, async (err, result) => {
            if (!err) {
                resolve(result);
            } else {
                reject(err);
            }
        });
    });

    // 查询数据
    let query_data = new Promise((resolve, reject) => {
        db.staff.find(query).sort(sort).skip(skip).limit(pageSize).toArray(async (err, result) => {
            if (!err) {
                resolve(result);
            } else {
                reject(err);
            }
        });
    });

    // 构造分页信息
    let buildPageInfo = (pageIndex, pageSize, totalCount) => {

        // let totalPage = (totalCount % pageSize > 0) ? parseInt(totalCount / pageSize) + 1 : Math.floor(totalCount / pageSize);

        // 向上取整
        let totalPage = Math.ceil(totalCount / pageSize);
        let nextPage = (pageIndex == totalPage) ? pageIndex : pageIndex + 1;
        let prePage = (pageIndex > 1) ? pageIndex - 1 : pageIndex;
        let lastResultIndex = pageIndex * pageSize - 1;
        let firstResultIndex = (pageIndex - 1) * pageSize;

        let pageInfo = {
            firstResultIndex: firstResultIndex,
            lastResultIndex: lastResultIndex,
            pageIndex: pageIndex,
            pageSize: pageSize,
            prePage: prePage,
            nextPage: nextPage,
            totalCount: totalCount,
            totalPage: totalPage
        };

        return pageInfo;
    };

    // 构造分页结果
    let buildPage = new Promise((resolve, reject) => {
        Promise.all([query_count, query_data]).then((datas) => {

            let totalCount = datas[0];
            let data = datas[1];

            console.log(data[0]);
            console.log(data[1]);

            let result = {
                pageDatas: data,
                pageInfo: buildPageInfo(pageIndex, pageSize, totalCount)
            };

            resolve(result);
        });

    });

    return buildPage;

};

const findById = async (id) => {
    return new Promise(function (resolve, reject) {
        db.staff.findOne({_id: helper.toObjectID(id)}, async (err, result) => {
            if (!err) {
                resolve(result);
            } else {
                reject(err);
            }
        });
    });
};

const insert = async (staff) => {

    // 处理site字段
    staff.site = new DBRef('site', helper.toObjectID(staff.site));
    staff.createdAt = new Date();
    return new Promise((resolve, reject) => {
        db.staff.insert(staff, async (err, result) => {
            if (!err) {
                resolve(result);
            } else {
                reject(err);
            }
        });
    });
};

const save = async (staff) => {
    // 处理city字段
    staff.site = new DBRef('site', helper.toObjectID(staff.site));
    staff.lastModifiedAt = new Date();
    return new Promise((resolve, reject) => {
        db.staff.save(staff, async (err, result) => {
            if (!err) {
                resolve(result);
            } else {
                reject(err);
            }
        });
    });
};

/**
 *
 * @param update
 * @returns {Promise}
 */
const update = async (query, update) => {
    return new Promise((resolve, reject) => {
        // update({查询字段},{修改部分},function(error,result){ //异步回掉函数 });
        db.staff.update(query, update, async (err, result) => {
            if (!err) {
                resolve(result);
            } else {
                reject(err);
            }
        });
    });
};

const findAndModify = async (query, update,) => {
    return new Promise((resolve, reject) => {
        // findAndModify({查询字段},[排序字段],{修改部分},{配置属性},function(error,result){ //异步回掉函数} });
        db.staff.findAndModify(query, {}, update, {new: true, upsert: true}, async (err, result) => {
            if (!err) {
                resolve(result);
            } else {
                reject(err);
            }
        });
    });
};

const delById = async (id) => {
    return new Promise(function (resolve, reject) {
        db.staff.remove({_id: helper.toObjectID(id)}, async (err, result) => {
            if (!err) {
                resolve(result);
            } else {
                reject(err);
            }
        });
    });
};


exports = module.exports = {
    findAll, findById, find, insert, save, delById, update, findAndModify, findBySite
};